#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include "pilot.h"

#define MAX_P 100
PI_PROCESS *C;
PI_PROCESS *D[MAX_P];
PI_CHANNEL *fromC;
PI_CHANNEL *toD[MAX_P];
PI_CHANNEL *fromD[MAX_P];
PI_BUNDLE *check;

int decompress (int index, void* arg2)
{
	int i;
	
	while(1) {
		PI_Read( toD[index], "%d", &i );
		printf("decompressing: %d\n", i);
		PI_Write( fromD[index], "%d", i );

		if (i == -1)
			break;
	}

	return 0;
}

int compress (int index, void *arg2)
{
	int c, i;

	while(1) {
		c = PI_Select(check);
		PI_Read( fromD[c], "%d", &i );
		printf("compressing: %d\n", i);

		if (i == -1)
			break;
	}

	return 0;
}

int main(int argc, char *argv[])
{
	int NO_PIPE = 0;
	int SERIAL_MODE = 0;
	char *inputDir, *outputDir;
	
	int P = 0;
	P = PI_Configure(&argc, &argv);
	
	/* set serial mode to true in event of one process */
	if (P == 1)
		SERIAL_MODE = 1;
	else if (P == 2) {
		printf("For Part 1 there cannot be only 2 processes.\n");
		return 1;
	}

	/* if there are an improper number of arguments */
	if (argc < 3 || argc > 4) {
		
		printf("Proper use:\n");
		printf("sqsub ... thumb [-nopipe] input-dir output-dir [Pilot options]\n");
		return 1;
	}
	
	/* if the no-pipe argument is included */
	if (argc == 4) {
		if (strcmp(argv[1], "-nopipe") == 0)
			NO_PIPE = 1;
		
		inputDir = malloc(sizeof(char) * strlen(argv[2]));
		outputDir = malloc(sizeof(char) * strlen(argv[3]));
		strcpy(inputDir, argv[2]);
		strcpy(outputDir, argv[3]);
	}
	
	/* if the no-pipe argument is not included */
	else {
		inputDir = malloc(sizeof(char) * strlen(argv[1]));
		outputDir = malloc(sizeof(char) * strlen(argv[2]));
		strcpy(inputDir, argv[1]);
		strcpy(outputDir, argv[2]);
	}
	   
	int i, toWrite = 0, numDs;
	int complete = 0, numFiles = 10;
	
	/*if (numFiles < P-2)
		numDs = numFiles;
	else
		numDs = P - 2;*/

	numDs = P - 2;

	//printf("Number of files: %d\n", numFiles);
	//printf("Number of decompressors: %d\n", numDs);
	   
	/* set up processes and communication */
	C = PI_CreateProcess(compress, 0, NULL);
	fromC = PI_CreateChannel(C, PI_MAIN);
	
	for (i = 0; i < numDs; i++) {
		D[i] = PI_CreateProcess(decompress, i, NULL);
		toD[i] = PI_CreateChannel(PI_MAIN, D[i]);
		
		if (NO_PIPE == 1)
			fromD[i] = PI_CreateChannel(D[i], PI_MAIN);
		else
			fromD[i] = PI_CreateChannel(D[i], C);
	}
	
	/* create the bundle */
	check = PI_CreateBundle(PI_SELECT, fromD, numDs);
	
	PI_StartAll();

	/* loop for every file in the input-dir */
	for (i = 0; i < numDs; i++) {
		
		/* write binnary jpeg data to decompressor */
		PI_Write(toD[i], "%d", i);
	}
	
	/* kill all the decompressors and compressors */
	int kill = -1;
	for (i = 0; i < numDs; i++) {
		PI_Write(toD[i], "%d", kill);
	}
	
	free(inputDir);
	free(outputDir);

	PI_StopMain(0);
	return 0;
}
